package com.ruoyi.framework.service;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class SmsUserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException
    {
        SysUser sysUser = new SysUser();
        sysUser.setPhonenumber(phone);
        List<SysUser> sysUsers = userService.selectUserList(sysUser);
        if (sysUsers.isEmpty())
        {
            log.info("登录手机号：{} 不存在.", phone);
            throw new UsernameNotFoundException("登录手机号：" + phone + " 不存在");
        }
        else if (UserStatus.DISABLE.getCode().equals(sysUsers.get(0).getStatus()))
        {
            log.info("登录用户：{} 已被停用.", phone);
            throw new GlobalException("对不起，您的账号：" + phone + " 已停用");
        }

        return createLoginUser(sysUsers.get(0));
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }
}
